package com.dbsop.domain.rest.agg;

import com.dbsop.domain.rest.info.RFFM;
import com.dbsop.domain.transport.res.TransportUtils;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * 范围分组
 */
public final class RestScopeGroup extends RestGroup {

    private List<RFFM> rffms = new ArrayList<RFFM>();

    public RestScopeGroup(String fieldName) {
        super(fieldName);
    }

    public RestScopeGroup(String fieldName, String formatName) {
        super(fieldName, formatName);
    }

    public void add(RFFM rffm){
        rffms.add(rffm);
    }

    @Override
    public AggregationBuilder aggregationBuilder() {
        RangeAggregationBuilder thisGroup
                = AggregationBuilders.range(formatName).field(fieldName);
        rffms.forEach(rffm -> {
            if (rffm.getFormat() == null){
                if (rffm.getStart() == null){
                    thisGroup.addUnboundedTo(rffm.getEnd());
                }else if (rffm.getEnd() == null){
                    thisGroup.addUnboundedFrom(rffm.getStart()).format();
                }else {
                    thisGroup.addRange(rffm.getStart(),rffm.getEnd());
                }
            }else {
                if (rffm.getStart() == null){
                    thisGroup.addUnboundedTo(rffm.getFormat(),rffm.getEnd());
                }else if (rffm.getEnd() == null){
                    thisGroup.addUnboundedFrom(rffm.getFormat(),rffm.getStart()).format();
                }else {
                    thisGroup.addRange(rffm.getFormat(),rffm.getStart(),rffm.getEnd());
                }
            }

        });

        if (group !=null)thisGroup.subAggregation(group.aggregationBuilder());
        if (aggOperations.size()>0){
            TransportUtils.paresAggregationBuilders(aggOperations)
                    .forEach(aggregationBuilder -> {
                        thisGroup.subAggregation(aggregationBuilder);
                    });
        }
        return thisGroup;
    }
}
